import {store_field_user_config, userConfigInfo} from "@/main/store/store.js";
import * as path from "node:path";
import {logger} from "@/main/log.js";

const {app, BrowserWindow, ipcMain, Menu} = require('electron')

const createMainWindow = () => {
    const windowConfig = getWindowConfig();
    const mainWindow = new BrowserWindow({
        width: windowConfig.width,
        height: windowConfig.height,
        autoHideMenuBar: true,
        titleBarStyle: 'hidden',
        icon: path.join(__dirname, '../../public/logo.png'),
        webPreferences: {
            webSecurity: false,
            preload: path.join(__dirname, '../preload/mainWindow.mjs'),
            sandbox: false,
            devTools: true,
        }
    })
    // 使用 loadFile 加载 electron/main-window.html 文件
    logger.debug(`当前应用打包情况${!app.isPackaged},当前环境:${process.env.NODE_ENV}`);
    logger.debug(`当前的环境为${process.env.NODE_ENV}`);
    if (process.env.NODE_ENV === "development") {
        // const url = `http://${import.meta.env.VITE_DEV_HOST}:${import.meta.env.VITE_DEV_PORT}/main-window.html`;
        const url = `${process.env['ELECTRON_RENDERER_URL']}/main-window.html`;
        logger.debug(`当前加载的网页地址为 ${url}`);
        mainWindow.loadURL(url, {});
        mainWindow.webContents.openDevTools();
    } else {
        mainWindow.loadFile(path.join(__dirname, '../renderer/main-window.html'));
        mainWindow.webContents.openDevTools();
    }

    mainWindow.customerId = 'mainWindow';

    ipcMain.on('window/main/close', (event, arg) => {
        mainWindow.destroy();
    })
    ipcMain.on('window/main/miniSize', (event, arg) => {
        mainWindow.minimize()
    })
}


const createDynamicWindow = () => {
    const mainWindow = new BrowserWindow({
        width: 500,
        height: 650,
        autoHideMenuBar: true,
        icon: path.join(__dirname, '../../public/logo.png'),
        webPreferences: {
            webSecurity: false,
            preload: path.join(__dirname, '../preload/dynamicWindow.mjs'),
            sandbox: false,
            devTools: true,
        }
    })
    // 使用 loadFile 加载 electron/main-window.html 文件
    if (process.env.NODE_ENV === "development") {
        // const url = `http://${import.meta.env.VITE_DEV_HOST}:${import.meta.env.VITE_DEV_PORT}/main-window.html`;
        const url = `${process.env['ELECTRON_RENDERER_URL']}/dynamic-window.html`;
        logger.debug(`当前加载的网页地址为 ${url}`);
        mainWindow.loadURL(url, {});
        mainWindow.webContents.openDevTools();
    } else {
        mainWindow.loadFile(path.join(__dirname, '../renderer/dynamic-window.html'));
    }
}

function getWindowConfig() {
    /**
     * {
     *     "width":
     *     "height":
     * }
     */
        //1440 900
        //1920 1080

    const obj = userConfigInfo.get(`${store_field_user_config}.mainWindowScreen`) ?? {
            "width": 1600,
            "height": 900,
        };

    return obj;
}

export {createMainWindow, createDynamicWindow}